import React, { useEffect } from 'react';
import add from './add.module.less';
import { Button, Form, Input, Select, Space, message } from 'antd';
import { addaccount } from "@/api/account";
const { Option } = Select;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

export default function Add() {
  const [form] = Form.useForm();

  //添加用户
  const adduser = async (data) => {
    try {
      const response = await addaccount(data);
      const { msg, code } = response;
      console.log(msg);
      if (code === 0) {
        message.success(msg); // 直接在函数中调用 message
      }
    } catch (error) {
      console.error('Error adding user:', error);
      message.error('添加用户失败');
    }
  };

  //提交表单
  const onFinish = values => {
    adduser(values);
    console.log(values);
  };

  //重置表单
  const onReset = () => {
    form.resetFields();
  };

  return (
    <div>
      <div className={add.title}>
        添加账号
      </div>
      <Form
        {...layout}
        form={form}
        name="control-hooks"
        onFinish={onFinish}
        style={{ maxWidth: 600, marginLeft: 50, marginTop: 50 }}
        layout="vertical"
      >
        <Form.Item name="account" label="账号" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item label="密码" name="password" rules={[{ required: true }]}>
          <Input.Password />
        </Form.Item>
        <Form.Item name="userGroup" label="用户组" rules={[{ required: true }]}>
          <Select
            placeholder="选择用户组"
            allowClear
          >
            <Option value="超级管理员">超级管理员</Option>
            <Option value="普通用户">普通用户</Option>
          </Select>
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
        >
          {({ getFieldValue }) =>
            getFieldValue('grop') === '普通用户' ? (
              <Form.Item name="customizeGender" label="Customize Gender" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            ) : null
          }
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" style={{ width: 100 }}>
              立即添加
            </Button>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
}